﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Objects;

namespace medder
{
    public partial class PatReg : Form
    {
        User user;
        MedBaseEntities med = new MedBaseEntities();
        public static ObjectSet<Patient> patients;
        public static ObjectSet<Insurance> insurances;
        public PatReg(User user)
        {
            InitializeComponent();
            this.user = user;
            insurances = med.Insurances;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string address = textBox1.Text;
            bool sex;
            if (RBMale.Checked)
                sex = true;
            sex = false;
            DateTime birthday = dateTimePicker1.Value;

            Patient patient = new Patient();
            patient.Address = address;
            patient.Sex = sex;
            patient.Birthday = birthday;
            patient.Passport = user.Passport;

            string insurance = MTBInsurance.Text;
            string insuranceCompany = textBox3.Text;
            DateTime insDate = dateTimePicker2.Value;

            if (CheckInsurance(insurance))
            {
                Insurance ins = new Insurance();
                ins.InsId = insurance;
                ins.InsName = insuranceCompany;
                ins.DueDate = insDate;
                med.AddToInsurances(ins);
                med.SaveChanges();

                patient.InsId = ins.InsId;

                med.AddToUsers(user);
                med.SaveChanges();

                patient.Passport = user.Passport;
                med.AddToPatients(patient);
                med.SaveChanges();
            }

            this.Close();
            SuccessReg fm = new SuccessReg(user);
            fm.ShowDialog();

        }

        private bool CheckInsurance(string insurance)
        {
            insurance = insurance.Trim();

            if (insurance.Equals(string.Empty))
            {
                Info1.Text = "Укажите медицинский полюс";
                return false;
            }
            if (insurances.Where(x => x.InsId == insurance).Count() == 0)
            {
                Info1.Text = string.Empty;
                return true;
            }
            else
            {
                button1.Enabled = false;
                Info1.Text = "Пациент с таким полюсом уже существует в базе";
                return false;
            }
        }
    }
}
